package cn.kmsoft.jssc.service;

import cn.kmsoft.jssc.config.AnalyseConfig;
import cn.kmsoft.jssc.entity.analyse.AnalyseDb;
import cn.kmsoft.jssc.entity.analyse.AnalyseServer;
import cn.kmsoft.jssc.entity.analyse.AnalyseTable;
import cn.kmsoft.wololo.object.query.GeoJsonQuery;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SingleAnalyseService {
	private static final Logger logger = LoggerFactory.getLogger(SingleAnalyseService.class);

	@Autowired
	private AnalyseConfig analyseConfig;

	/**
	 * 转发空间分析请求
	 *
	 * @param dbKey  数据库标识
	 * @param tableName     数据库表名
	 * @param query         geoJsonQuery
	 * @return
	 */
	public JSONObject relayAnalyse(String dbKey, String tableName, GeoJsonQuery query) {
		//1、参数配置
		AnalyseTable analyseTable= this.analyseConfig.getAnalyseTableByTablename(dbKey,tableName);
		AnalyseDb analyseDb = this.analyseConfig.getAnalyseDbByDbkey(dbKey);
		String serverId = analyseDb.getServerId();
		AnalyseServer analyseServer = this.analyseConfig.getAnalyseServerByServerId(serverId);
		String analystServer = analyseServer.getServerUrl();
		//String analystServer = this.analyseServer.getServerUrl();

		String instanceName = analyseDb.getDbInstance();
		String tableSpace = analyseDb.getTablespace();;//默认SDE
		String analystType = this.analyseConfig.getAnalystTypes().get("py");//intersectpy
		String tableId = instanceName + "/" + tableSpace + "." + tableName;
		String targetUrl = analystServer 
				+ "/"+ analystType 
				+ "/" + tableId;
		
		String queryJsonStr = JSONObject.toJSONString(query);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		
		HttpEntity<String> entity = new HttpEntity<>(queryJsonStr, headers);
		
		//2、转发空间分析的请求
		ResponseEntity<JSONObject> exchange = this.exchangeSpatialAnalyst(targetUrl, entity);
		JSONObject resJson = exchange.getBody();
		
		return resJson;
	}
	
	protected ResponseEntity<JSONObject> exchangeSpatialAnalyst(String targetUrl, HttpEntity<String> entity){
		 RestTemplate restTemplate = new RestTemplate();
		 ResponseEntity<JSONObject> exchange = restTemplate.exchange(targetUrl, HttpMethod.POST, entity, JSONObject.class);
		 
		 return exchange;
	}

}
